﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using System.Diagnostics;
using System.IO;
using System.Collections;
using Newtonsoft.Json;
using Sunny.UI;
using System.Text.RegularExpressions;



namespace bilibiliFFmpeg
{
    public partial class Main : UIForm
    {
        private AboutUs aboutForm;
        private settings settingsForm;
        public string m4sVideo, m4sAudio, mp4output;
        public static string exePath = Environment.CurrentDirectory;//获取当前工作目录  EXE文件目录
        public string completePath = exePath + @"\合并完成目录\";//合并完成目录

        public int viewpd = 0;//页面判断

        public string canName;

        public static UIDataGridView dataGridView;
        List<List_Adapte> dataAdapte = new List<List_Adapte>();
        List<InfoVo> list = new List<InfoVo>();


        //去除一些特殊的字符的正则表达式
        public static String regEx1 = @"[^a-zA-Z0-9\u4e00-\u9fa5]";//   只留下字母和汉字






        private void cs1(object sender, EventArgs e)
        {
            //int row = dataGridView.Rows.Count;//得到总行数
            foreach (DataGridViewRow i in dataGridView.Rows)
            {
                //MessageBox.Show(i.Index+i.Cells[0].Value.ToString());
                if (i.Cells[0].Value.ToString().Equals("true"))
                {
                    dataAdapte.Add(new List_Adapte(i.Cells[1].Value.ToString(), i.Cells[2].Value.ToString()));
                }
            }


            foreach (List_Adapte item in dataAdapte)
            {

            }



            //MessageBox.Show(dataGridView.SelectedCells[1].Value.ToString() + dataGridView.SelectedCells[2].Value.ToString());

        }


        //双击dataGridViewItem
        public void dataGridViewItemDoubleClick(object sender, DataGridViewCellEventArgs e)
        {
            if (viewpd != 1)
            {
                viewpd = 1;//页面判断

                dataAdapte.Clear();//清理适配器
                try
                {
                    string name = dataGridView.SelectedCells[1].Value.ToString().Replace(regEx1, "");
                    string path = dataGridView.SelectedCells[2].Value.ToString();
                    canName = name;
                    //MessageBox.Show(completePath + name);



                    ergodicDirBackPath.clearPath();//清除残留数据

                    showPath.Text = path;//设置显示路径
                    //获取P的名称下的danmaku.xml、audio.m4s、video.m4s
                    //ergodicDirBackPath.ergodicDirBackPathAboutm4s(showPath.Text);
                    //获取标题的P名称和路径
                    ergodicDirBackPath.getJsonFZ(showPath.Text);

                    dataGridView.DataSource = null;  //清理dataGridView里面的items
                    list.Clear();//清理dataGridViewItem里的数据

                    foreach (nameApath i1 in ergodicDirBackPath.json_pathList)
                    {
                        list.Add(new InfoVo() { itemChoose = false, itemName = i1.getName(), itemPath = i1.getPath() });
                    }
                    dataGridView.DataSource = list;//设置dataGridView里面的items
                    dataGridView.Columns[0].HeaderCell.Value = "选择";//设置header
                    dataGridView.Columns[1].HeaderCell.Value = "名称";
                    dataGridView.Columns[2].HeaderCell.Value = "路径";
                }
                catch (Exception e1)
                {
                    ShowErrorDialog("解析数据失败！");
                    ShowErrorDialog(e1.ToString());
                    //MessageBox.Show("解析数据失败！");
                    //MessageBox.Show(e1.ToString());
                }
            }
        }



        private void cs(object sender, EventArgs e)
        {



        }











        private void showInitViewByPath(string sPath)
        {

            ergodicDirBackPath.clearPath();//清除残留数据

            showPath.Text = sPath;//设置显示路径
            //获取P的名称下的danmaku.xml、audio.m4s、video.m4s
            //ergodicDirBackPath.ergodicDirBackPathAboutm4s(showPath.Text);
            //获取标题的名称和路径

            dataGridView.DataSource = null;  //清理dataGridView里面的items
            list.Clear();//清理dataGridViewItem里的数据

            ergodicDirBackPath.roughlyReadJson(showPath.Text);

            if (ergodicDirBackPath.json_pathList.Count != 0)
            {
                foreach (nameApath i1 in ergodicDirBackPath.json_pathList)
                {
                    list.Add(new InfoVo() { itemChoose = false, itemName = i1.getName(), itemPath = i1.getPath() });
                    //dataGridView.AutoGenerateColumns = false;
                }
                dataGridView.DataSource = list;
                dataGridView.Columns[0].HeaderCell.Value = "选择";//设置header
                dataGridView.Columns[1].HeaderCell.Value = "名称";
                dataGridView.Columns[2].HeaderCell.Value = "路径";

            }
            else
            {
                viewpd = 1;
                dataAdapte.Clear();
                try
                {
                    string path = showPath.Text;
                    //MessageBox.Show("8888");
                    string name = ergodicDirBackPath.roughlyPNameByReadJson(path);
                    //MessageBox.Show("9999");
                    canName = name;
                    //MessageBox.Show(completePath + name);

                    ergodicDirBackPath.clearPath();//清除残留数据

                    showPath.Text = path;//设置显示路径
                    //获取P的名称下的danmaku.xml、audio.m4s、video.m4s
                    //获取标题的P名称和路径
                    ergodicDirBackPath.getJsonFZ(showPath.Text);

                    dataGridView.DataSource = null;  //清理dataGridView里面的items
                    list.Clear();//清理dataGridViewItem里的数据

                    foreach (nameApath i1 in ergodicDirBackPath.json_pathList)
                    {
                        list.Add(new InfoVo() { itemChoose = false, itemName = i1.getName(), itemPath = i1.getPath() });
                    }

                    dataGridView.DataSource = list;

                    dataGridView.Columns[0].HeaderCell.Value = "选择";//设置header
                    dataGridView.Columns[1].HeaderCell.Value = "名称";
                    dataGridView.Columns[2].HeaderCell.Value = "路径";
                }
                catch (Exception e1)
                {
                    ShowErrorDialog("解析数据失败！");
                    ShowErrorDialog(e1.ToString());
                    //MessageBox.Show("解析数据失败！");
                    //MessageBox.Show(e1.ToString());
                }

            }

        }





        //选择路径按钮
        private void choosePath_Click(object sender, EventArgs e)
        {

            if (fileBrowserDialog.ShowDialog() == DialogResult.OK) //选择路径弹窗   获取路径
            {
                showInitViewByPath(fileBrowserDialog.SelectedPath);
            }
            else
            {
                ShowWarningTip("您没有选择目录哦！", 1500, true);
            }

        }






        public Main()
        {
            InitializeComponent();

            dataGridView = dataGridView_nameApath;//获取dataGridView_nameApath
            dataGridView.DataSource = null;  //清理dataGridView里面的items


            //m4sVideo = Environment.CurrentDirectory + @"\ffmpeg\video.m4s";
            //m4sAudio = Environment.CurrentDirectory + @"\ffmpeg\audio.m4s";
            //mp4output = Environment.CurrentDirectory + @"\ffmpeg\1.mp4";
            //Run(m4sVideo, m4sAudio, mp4output);
        }
        public void clearAVO()
        {
            m4sAudio = "";
            m4sVideo = "";
            mp4output = "";
        }
        //执行ffmpeg命令 所有的都为全路径
        public bool Run(String inputVideo, String inputAudio, String outputPath,String type)
        {

            bool isok = false;//是否成功
            //Environment.CurrentDirectory      //获取当前程序（exe）所在路径
            //ffmpeg -i video.m4s -i audio.m4s -c copy 1.mp4
            //必须为全路径
            string watermark="";

            switch (type)
            {
                case "m4s":
                    watermark = "-i " + inputVideo + " -i " + inputAudio + " -c copy " + outputPath;
                    break;
                case "blv":
                    watermark = "-f concat -safe 0 -i " + inputAudio + " -c copy " + outputPath;
                    break;
                default:
                    break;
            }

            
             

            //MessageBox.Show(watermark);

            Process p = new Process();//建立外部调用线程
            p.StartInfo.FileName = Environment.CurrentDirectory + @"\ffmpeg\ffmpeg.exe";//获取ffmpeg.exe执行文件

            p.StartInfo.Arguments = watermark; //参数(这里就是FFMPEG的参数了) 
            p.StartInfo.UseShellExecute = false;//不使用操作系统外壳程序启动线程(一定为FALSE,详细的请看MSDN)
            p.StartInfo.RedirectStandardError = true;//把外部程序错误输出写到StandardError流中(这个一定要注意,FFMPEG的所有输出信息,都为错误输出流,用StandardOutput是捕获不到任何消息的
            p.StartInfo.CreateNoWindow = true;//不创建进程窗口
            try
            {

                p.ErrorDataReceived += new DataReceivedEventHandler(Output);//外部程序(这里是FFMPEG)输出流时候产生的事件,这里是把流的处理过程转移到下面的方法中,详细请查阅MSDN
                p.Start();//启动线程
                p.BeginErrorReadLine();//开始异步读取

                p.WaitForExit();//阻塞等待进程结束
            }
            catch (Exception exp)
            {
                Console.WriteLine(exp.Message);
                return isok;
            }
            finally
            {
                if (p.HasExited && p.ExitCode == 1)
                    isok = false;
                else
                    isok = true;
                p.Close();//关闭进程
                p.Dispose();//释放资源
            }
            return isok;
        }

        private static void Output(object sendProcess, DataReceivedEventArgs output)
        {
            Process p = sendProcess as Process;
            if (p.HasExited && p.ExitCode == 1) // 在ffmpeg发生错误的时候才输出信息
            {
                Console.WriteLine(output.Data);
                Console.ReadLine();
                //throw new Exception("视频处理失败");
            }
        }


        //合并按钮
        private void button_merge_Click(object sender, EventArgs e)
        {
            List<Boolean> result_pd = new List<Boolean>();
            int number_err = 0;

            dataAdapte.Clear();
            foreach (DataGridViewRow i in dataGridView.Rows)
            {
                //MessageBox.Show(i.Index+i.Cells[0].Value.ToString());
                if (i.Cells[0].Value.ToString().Equals("True"))
                {
                    //MessageBox.Show(i.Cells[1].Value.ToString() + i.Cells[2].Value.ToString());
                    dataAdapte.Add(new List_Adapte(i.Cells[1].Value.ToString(), i.Cells[2].Value.ToString()));
                }
            }

            if (dataAdapte.Count == 0)
            {
                ShowWarningTip("您还没勾选嘤~~~，就是前面打勾勾", 1700, true);
                //MessageBox.Show("您还没勾选嘤~~~");
            }
            else
            {
                ShowWaitForm("正在进行合并，请稍后......");

                

                switch (viewpd)
                {
                    case 0://标题合并
                        //listV.CheckedItems[0].SubItems[0].Text  名称
                        //listV.CheckedItems[0].SubItems[1].Text  路径
                        //MessageBox.Show(listV.CheckedItems.Count + "");
                        for (int i2 = 0; i2 < dataAdapte.Count; i2++)
                        {

                            SetWaitFormDescription(UILocalize.SystemProcessing + (i2 + 1) / (dataAdapte.Count + 1));

                            //MessageBox.Show("名称是:" + listV.CheckedItems[i2].SubItems[0].Text + "路径是:" + listV.CheckedItems[i2].SubItems[1].Text);
                            string name = dataAdapte[i2].getName().Replace(regEx1, "");
                            string path = dataAdapte[i2].getPath();
                            string outFile;//合并mp4文件全路径

                            ergodicDirBackPath.clearPath();//清除残留数据
                            //获取P的名称下的danmaku.xml、audio.m4s、video.m4s
                            //ergodicDirBackPath.ergodicDirBackPathAboutm4s(showPath.Text);
                            //获取标题的P名称和路径
                            ergodicDirBackPath.getJsonFZ(path);
                            fileUtil.creatDir(completePath + name);

                            foreach (nameApath i1 in ergodicDirBackPath.json_pathList)
                            {
                                clearAVO();//清除残留
                                
                                ergodicDirBackPath.style_blv.Clear();
                                ergodicDirBackPath.ergodicDirBackPathAboutm4s(i1.getPath());
                                fileUtil.writeTextByList(ergodicDirBackPath.blv_txtPath, ergodicDirBackPath.style_blv);
                                outFile = completePath + name + @"\" + i1.getName() + ".mp4";
                                if (fileUtil.fileExists(outFile))
                                {
                                    ShowWarningTip(outFile + "-------已经存在", 1500, true);
                                    //MessageBox.Show(outFile + "-------已经存在");
                                }
                                else
                                {
                                    if (ergodicDirBackPath.style_blv.Count != 0)
                                    {
                                        result_pd.Add(Run("", ergodicDirBackPath.blv_txtPath + @"\blv.txt", outFile, "blv"));
                                    }
                                    else
                                    {
                                        result_pd.Add(Run(ergodicDirBackPath.inputVideo, ergodicDirBackPath.inputAudio, outFile, "m4s"));
                                    }
                                }
                            }

                        }
                        break;
                    case 1:
                        //P合并
                        //listV.CheckedItems[0].SubItems[0].Text  名称
                        //listV.CheckedItems[0].SubItems[1].Text  路径
                        for (int i2 = 0; i2 < dataAdapte.Count; i2++)
                        {

                            SetWaitFormDescription(UILocalize.SystemProcessing + (i2 + 1) / (dataAdapte.Count + 1));

                            //MessageBox.Show("名称是:" + listV.CheckedItems[i2].SubItems[0].Text + "路径是:" + listV.CheckedItems[i2].SubItems[1].Text);
                            string name = dataAdapte[i2].getName().Replace(regEx1, "");
                            string path = dataAdapte[i2].getPath();
                            string outFile;//合并mp4文件全路径

                            ergodicDirBackPath.clearPath();//清除残留数据
                            //获取P的名称下的danmaku.xml、audio.m4s、video.m4s
                            //ergodicDirBackPath.ergodicDirBackPathAboutm4s(showPath.Text);

                            fileUtil.creatDir(completePath + canName);

                            clearAVO();//清除残留
                            //获取标题的P名称和路径
                            ergodicDirBackPath.ergodicDirBackPathAboutm4s(path);


                            fileUtil.writeTextByList(ergodicDirBackPath.blv_txtPath, ergodicDirBackPath.style_blv);



                            outFile = completePath + canName + @"\" + name + ".mp4";
                            if (fileUtil.fileExists(outFile))
                            {
                                ShowWarningTip(outFile + "-------已经存在", 1500, true);
                                //MessageBox.Show(outFile + "-------已经存在");
                            }
                            else
                            {
                                if (ergodicDirBackPath.style_blv.Count!=0)
                                {
                                    result_pd.Add(Run("", ergodicDirBackPath.blv_txtPath + @"\blv.txt", outFile, "blv"));
                                }
                                else
                                {
                                    result_pd.Add(Run(ergodicDirBackPath.inputVideo, ergodicDirBackPath.inputAudio, outFile, "m4s"));
                                }
                                
                            }
                        }
                        break;
                    default:
                        break;
                }

                HideWaitForm();
                //统计失败的个数
                for (int i3 = 0; i3 < result_pd.Count; i3++)
                {
                    if (!result_pd[i3])
                    {
                        number_err++;
                    }
                }
                if ((result_pd.Count - number_err) == 0 && number_err == 0)
                {

                }
                else
                {
                    UIMessageDialog.ShowMessageDialog("合并成功:" + (result_pd.Count - number_err) + "个，合并失败:" + number_err + "个。\n\tPS（如果合并失败请查看软件安装目录是否存在空格以及特殊字符，存在则会导致合并失败）\n\t如果合并失败请检查路径：" + Main.exePath, "提示", false, Style);
                }

            }


        }



        //加载listview
        public void loadingListView(string path)
        {

            ergodicDirBackPath.clearPath();//清除残留数据

            showPath.Text = path;//设置显示路径
            //获取标题的名称和路径
            ergodicDirBackPath.roughlyReadJson(showPath.Text);

            dataGridView.DataSource = null;  //清理dataGridView里面的items
            list.Clear();//清理dataGridViewItem里的数据


            foreach (nameApath i1 in ergodicDirBackPath.json_pathList)
            {
                list.Add(new InfoVo() { itemChoose = false, itemName = i1.getName(), itemPath = i1.getPath() });
            }

            dataGridView.DataSource = list;

            dataGridView.Columns[0].HeaderCell.Value = "选择";//设置header
            dataGridView.Columns[1].HeaderCell.Value = "名称";
            dataGridView.Columns[2].HeaderCell.Value = "路径";

        }

        private void btn_refresh_Click(object sender, EventArgs e)
        {
            showInitViewByPath(showPath.Text);
            //loadingListView(showPath.Text);
        }
        //单击item---弃用
        public void listviewItemClick(object sender, EventArgs e)
        {
            //if (listV.SelectedItems.Count != 1)
            //    return;
            //else
            //{
            //    //选中点击那一行的第一列的值，索引值必须是0，而且无论点这一行的第几列，选中的都是这一行第一列的值 ，如果想获取这一行除第一列外的值，则用subitems获取，[]中为索引，从1开始。
            //    string name = listV.SelectedItems[0].Text.Replace(regEx1, "");
            //    string path = listV.SelectedItems[0].SubItems[1].Text;
            //    string outFile;//合并mp4文件全路径

            //    listV.Items.Clear();//清理listview里面的items
            //    ergodicDirBackPath.clearPath();//清除残留数据


            //    //获取P的名称下的danmaku.xml、audio.m4s、video.m4s
            //    //ergodicDirBackPath.ergodicDirBackPathAboutm4s(showPath.Text);
            //    //获取标题的P名称和路径
            //    ergodicDirBackPath.getJsonFZ(showPath.Text);
            //    fileUtil.creatDir(completePath + name);


            //    //listV.BeginUpdate();  //数据更新，UI暂时挂起，直到EndUpdate绘制控件，可以有效避免闪烁并大大提高加载速度
            //    foreach (nameApath i1 in ergodicDirBackPath.json_pathList)
            //    {
            //        clearAVO();//清除残留
            //        ergodicDirBackPath.ergodicDirBackPathAboutm4s(i1.getPath());
            //        outFile = completePath + name + @"\" + i1.getName() + ".mp4";
            //        if (fileUtil.fileExists(outFile))
            //        {
            //            MessageBox.Show(outFile + "-------已经存在");
            //        }
            //        else
            //        {
            //            Run(ergodicDirBackPath.inputVideo, ergodicDirBackPath.inputAudio, outFile);
            //        }



            //    }
            //    //listV.EndUpdate();  //结束数据处理，UI界面一次性绘制。



            //    //MessageBox.Show(name+path);
            //}

        }
        //双击item-----弃用
        public void listviewItemDoubleClick(object sender, MouseEventArgs e)
        {
            //if (viewpd != 1)
            //{
            //    viewpd = 1;
            //    for (int i2 = 0; i2 < listV.Items.Count; i2++)
            //    {
            //        listV.Items[i2].Checked = false;//去除上个页面选择的
            //    }

            //    ListViewHitTestInfo info = listV.HitTest(e.X, e.Y);
            //    if (info.Item != null)
            //    {
            //        try
            //        {
            //            string name = info.Item.Text.Replace(regEx1, "");
            //            string path = info.Item.SubItems[1].Text;
            //            canName = name;
            //            //MessageBox.Show(completePath + name);

            //            listV.Items.Clear();//清理listview里面的items
            //            ergodicDirBackPath.clearPath();//清除残留数据

            //            showPath.Text = path;//设置显示路径
            //            //获取P的名称下的danmaku.xml、audio.m4s、video.m4s
            //            //ergodicDirBackPath.ergodicDirBackPathAboutm4s(showPath.Text);
            //            //获取标题的P名称和路径
            //            ergodicDirBackPath.getJsonFZ(showPath.Text);

            //            listV.BeginUpdate();  //数据更新，UI暂时挂起，直到EndUpdate绘制控件，可以有效避免闪烁并大大提高加载速度
            //            foreach (nameApath i1 in ergodicDirBackPath.json_pathList)
            //            {
            //                ListViewItem lvi = new ListViewItem();

            //                lvi.Text = i1.getName();

            //                lvi.SubItems.Add(i1.getPath());

            //                listV.Items.Add(lvi);

            //            }
            //            listV.EndUpdate();  //结束数据处理，UI界面一次性绘制。
            //        }
            //        catch (Exception e1)
            //        {
            //            MessageBox.Show("解析数据失败！");
            //            MessageBox.Show(e1.ToString());
            //        }


            //    }
            //}
        }
        //打开合并完成文件目录
        private void btn_completeFile_Click(object sender, EventArgs e)
        {
            System.Diagnostics.Process.Start(exePath + @"\合并完成目录");
        }

        private void btn_checkAll_Click(object sender, EventArgs e)
        {
            foreach (DataGridViewRow i in dataGridView.Rows)
            {
                i.Cells[0].Value = true;
                //MessageBox.Show(i.Index+i.Cells[0].Value.ToString());
                //i.Cells[0].Value.ToString();

            }
            dataGridView.DataSource = list;
            dataGridView.Columns[0].HeaderCell.Value = "选择";//设置header
            dataGridView.Columns[1].HeaderCell.Value = "名称";
            dataGridView.Columns[2].HeaderCell.Value = "路径";

            //for (int i2 = 0; i2 < list.Count; i2++)
            //{
            //    list[i2].itemChoose = true;
            //}
        }
        //取消全选
        private void btn_deselectAll_Click(object sender, EventArgs e)
        {

            foreach (DataGridViewRow i in dataGridView.Rows)
            {
                i.Cells[0].Value = false;
                //MessageBox.Show(i.Index+i.Cells[0].Value.ToString());
                //i.Cells[0].Value.ToString();

            }
            dataGridView.DataSource = list;
            dataGridView.Columns[0].HeaderCell.Value = "选择";//设置header
            dataGridView.Columns[1].HeaderCell.Value = "名称";
            dataGridView.Columns[2].HeaderCell.Value = "路径";

            //for (int i2 = 0; i2 < list.Count; i2++)
            //{
            //    list[i2].itemChoose = false;
            //}
        }
        //返回按钮
        private void btn_back_Click(object sender, EventArgs e)
        {
            try
            {
                if (viewpd != 0)
                {
                    viewpd = 0;//页面判断
                    btn_deselectAll_Click(sender, e);

                    //MessageBox.Show("获取路径失败！");

                    dataGridView.DataSource = null; //清理listview里面的items
                    ergodicDirBackPath.clearPath();//清除残留数据

                    int lastx = showPath.Text.LastIndexOf(@"\");


                    showPath.Text = showPath.Text.Remove(lastx);
                    //获取标题的名称和路径
                    ergodicDirBackPath.roughlyReadJson(showPath.Text);

                    dataGridView.DataSource = null;  //清理dataGridView里面的items
                    list.Clear();//清理dataGridViewItem里的数据

                    foreach (nameApath i1 in ergodicDirBackPath.json_pathList)
                    {
                        list.Add(new InfoVo() { itemChoose = false, itemName = i1.getName(), itemPath = i1.getPath() });
                    }


                    dataGridView.DataSource = list;

                    dataGridView.Columns[0].HeaderCell.Value = "选择";//设置header
                    dataGridView.Columns[1].HeaderCell.Value = "名称";
                    dataGridView.Columns[2].HeaderCell.Value = "路径";

                }
            }
            catch (Exception e2)
            {

                
            }
        }

        //拖拽获取路径
        private void showPath_DragDrop(object sender, DragEventArgs e)
        {
            //GetValue(0) 为第1个文件全路径
            //DataFormats 数据的格式，下有多个静态属性都为string型，除FileDrop格式外还有Bitmap,Text,WaveAudio等格式
            string path = ((System.Array)e.Data.GetData(DataFormats.FileDrop)).GetValue(0).ToString();
            showPath.Text = path;
            showInitViewByPath(showPath.Text);
            showPath.Cursor = System.Windows.Forms.Cursors.IBeam; //还原鼠标形状
        }

        private void showPath_DragEnter(object sender, DragEventArgs e)
        {
            if (e.Data.GetDataPresent(DataFormats.FileDrop))
            {
                e.Effect = DragDropEffects.Link;
                showPath.Cursor = System.Windows.Forms.Cursors.Arrow;  //指定鼠标形状（更好看）  
            }
            else
            {
                e.Effect = DragDropEffects.None;
            }

        }

        //开始关于我们
        private void MenuItem_aboutUs_Click(object sender, EventArgs e)
        {
            aboutForm = new AboutUs();
            this.Hide();
            aboutForm.ShowDialog();
            this.Show();
            //Application.ExitThread();
        }
        //开始     退出
        private void MenuItem_exit_Click(object sender, EventArgs e)
        {
            Application.ExitThread();
        }
        //开始    选择合并目录
        private void MenuItem_choosPath_Click(object sender, EventArgs e)
        {
            choosePath_Click(sender, e);
        }


        //设置
        private void MenuItem_settings_Click(object sender, EventArgs e)
        {
            settingsForm = new settings();
            this.Hide();
            settingsForm.ShowDialog();
            this.Show();
        }

        private void Main_Load(object sender, EventArgs e)
        {
            //fileUtil.copyAudio();
            //new settings().btn_updata_Click(sender, e);
            if (!Directory.Exists(exePath + @"\合并完成目录"))
            {
                fileUtil.creatDir(exePath + @"\合并完成目录");
                MenuItem_aboutUs_Click(sender, e);
            }
            string xmlConfigPath = exePath + @"\config.xml";//配置文件路径

            if (!fileUtil.fileExists(xmlConfigPath))//初始化配置文件
            {
                XML.createXml(xmlConfigPath);
            }

            try
            {
                if (XML.readXml(xmlConfigPath, "updataPrompt").Equals("true"))
                {
                    new settings().btn_updata_Click(sender, e);
                }

                if (DateTime.Now.DayOfYear % 2 == 0)
                {
                    XML.changeXml(xmlConfigPath, "updataPrompt", "true");
                }
                else
                {
                    XML.changeXml(xmlConfigPath, "updataPrompt", "false");
                }
                
                //XML.changeXml(xmlConfigPath, "updataPrompt", "false");
            }
            catch (Exception e4)
            {
                XML.createXml(xmlConfigPath);
            }
            
            
            

        }

        private void button_audio_Click(object sender, EventArgs e)
        {
            List<Boolean> result_pd = new List<Boolean>();
            int number_err = 0;

            dataAdapte.Clear();
            foreach (DataGridViewRow i in dataGridView.Rows)
            {
                //MessageBox.Show(i.Index+i.Cells[0].Value.ToString());
                if (i.Cells[0].Value.ToString().Equals("True"))
                {
                    //MessageBox.Show(i.Cells[1].Value.ToString() + i.Cells[2].Value.ToString());
                    dataAdapte.Add(new List_Adapte(i.Cells[1].Value.ToString(), i.Cells[2].Value.ToString()));
                }
            }

            if (dataAdapte.Count == 0)
            {
                ShowWarningTip("您还没勾选嘤~~~，就是前面打勾勾", 1700, true);
                //MessageBox.Show("您还没勾选嘤~~~");
            }
            else
            {
                ShowWaitForm("正在提取音频，请稍后......");



                switch (viewpd)
                {
                    case 0://标题合并
                        //listV.CheckedItems[0].SubItems[0].Text  名称
                        //listV.CheckedItems[0].SubItems[1].Text  路径
                        //MessageBox.Show(listV.CheckedItems.Count + "");
                        for (int i2 = 0; i2 < dataAdapte.Count; i2++)
                        {

                            SetWaitFormDescription(UILocalize.SystemProcessing + (i2 + 1) / (dataAdapte.Count + 1));

                            //MessageBox.Show("名称是:" + listV.CheckedItems[i2].SubItems[0].Text + "路径是:" + listV.CheckedItems[i2].SubItems[1].Text);
                            string name = dataAdapte[i2].getName().Replace(regEx1, "");
                            string path = dataAdapte[i2].getPath();
                            string outFile;//合并mp4文件全路径

                            ergodicDirBackPath.clearPath();//清除残留数据
                            //获取P的名称下的danmaku.xml、audio.m4s、video.m4s
                            //ergodicDirBackPath.ergodicDirBackPathAboutm4s(showPath.Text);
                            //获取标题的P名称和路径
                            ergodicDirBackPath.getJsonFZ(path);
                            fileUtil.creatDir(completePath + name);

                            foreach (nameApath i1 in ergodicDirBackPath.json_pathList)
                            {
                                clearAVO();//清除残留

                                ergodicDirBackPath.style_blv.Clear();
                                ergodicDirBackPath.ergodicDirBackPathAboutm4s(i1.getPath());
                                fileUtil.writeTextByList(ergodicDirBackPath.blv_txtPath, ergodicDirBackPath.style_blv);


                                outFile = completePath + name + @"\" + i1.getName() + ".mp3";


                                if (fileUtil.fileExists(outFile))
                                {
                                    ShowWarningTip(outFile + "-------已经存在", 1500, true);
                                    //MessageBox.Show(outFile + "-------已经存在");
                                }
                                else
                                {
                                    if (ergodicDirBackPath.style_blv.Count != 0)
                                    {
                                        //result_pd.Add(Run("", ergodicDirBackPath.blv_txtPath + @"\blv.txt", outFile, "blv"));
                                        result_pd.Add(false);
                                    }
                                    else
                                    {
                                        //result_pd.Add(Run(ergodicDirBackPath.inputVideo, ergodicDirBackPath.inputAudio, outFile, "m4s"));
                                        result_pd.Add(fileUtil.copyAudio(ergodicDirBackPath.inputAudio, outFile));
                                    }
                                }
                            }

                        }
                        break;
                    case 1:
                        //P合并
                        //listV.CheckedItems[0].SubItems[0].Text  名称
                        //listV.CheckedItems[0].SubItems[1].Text  路径
                        for (int i2 = 0; i2 < dataAdapte.Count; i2++)
                        {

                            SetWaitFormDescription(UILocalize.SystemProcessing + (i2 + 1) / (dataAdapte.Count + 1));

                            //MessageBox.Show("名称是:" + listV.CheckedItems[i2].SubItems[0].Text + "路径是:" + listV.CheckedItems[i2].SubItems[1].Text);
                            string name = dataAdapte[i2].getName().Replace(regEx1, "");
                            string path = dataAdapte[i2].getPath();
                            string outFile;//合并mp4文件全路径

                            ergodicDirBackPath.clearPath();//清除残留数据
                            //获取P的名称下的danmaku.xml、audio.m4s、video.m4s
                            //ergodicDirBackPath.ergodicDirBackPathAboutm4s(showPath.Text);

                            fileUtil.creatDir(completePath + canName);

                            clearAVO();//清除残留
                            //获取标题的P名称和路径
                            ergodicDirBackPath.ergodicDirBackPathAboutm4s(path);


                            fileUtil.writeTextByList(ergodicDirBackPath.blv_txtPath, ergodicDirBackPath.style_blv);



                            outFile = completePath + canName + @"\" + name + ".mp3";
                            if (fileUtil.fileExists(outFile))
                            {
                                ShowWarningTip(outFile + "-------已经存在", 1500, true);
                                //MessageBox.Show(outFile + "-------已经存在");
                            }
                            else
                            {
                                if (ergodicDirBackPath.style_blv.Count != 0)
                                {
                                    //result_pd.Add(Run("", ergodicDirBackPath.blv_txtPath + @"\blv.txt", outFile, "blv"));
                                    result_pd.Add(false);
                                }
                                else
                                {
                                    //result_pd.Add(Run(ergodicDirBackPath.inputVideo, ergodicDirBackPath.inputAudio, outFile, "m4s"));
                                    result_pd.Add(fileUtil.copyAudio(ergodicDirBackPath.inputAudio, outFile));
                                }

                            }
                        }
                        break;
                    default:
                        break;
                }

                HideWaitForm();
                //统计失败的个数
                for (int i3 = 0; i3 < result_pd.Count; i3++)
                {
                    if (!result_pd[i3])
                    {
                        number_err++;
                    }
                }
                if ((result_pd.Count - number_err) == 0 && number_err == 0)
                {

                }
                else
                {
                    UIMessageDialog.ShowMessageDialog("提取成功:" + (result_pd.Count - number_err) + "个，提取失败:" + number_err + "个。\n\n\tPs（暂不支持旧版blv格式的提取）", "提示", false, Style);
                }

            }
        }






    }







    //文件操作工具类
    public class fileUtil
    {
        //创建目录
        public static void creatDir(string path)
        {
            if (!Directory.Exists(path))
            {
                Directory.CreateDirectory(path);
            }
        }

        //判断文件是否存在
        public static bool fileExists(string path)
        {
            if (File.Exists(path))
            {
                return true;
            }
            else
            {
                return false;
            }

        }

        public static bool copyAudio(string sourcePath,string targetPath)
        {
            try
            {
                bool isrewrite = true; // true=覆盖已存在的同名文件,false则反之
                File.Copy(sourcePath, targetPath, isrewrite);
            }
            catch (Exception e5)
            {
                return false;
            }
            return true;
        }

        public static void writeTextByList(string path,List<String> content)
        {

            FileStream fs = new FileStream(path + @"\blv.txt", FileMode.Create);
            StreamWriter sw = new StreamWriter(fs);
            //开始写入


            foreach (string s in content)
            {
                sw.WriteLine("file '" + s+"'");
            }


            //清空缓冲区
            sw.Flush();
            //关闭流
            sw.Close();
            fs.Close();
        }



    }






    //封装名称和路径
    public class nameApath
    {
        private String name;
        private String path;///download/1111

        public String getName()
        {
            return name;
        }

        public String getPath()
        {
            return path;
        }

        public nameApath(String name, String path)
        {
            this.name = name;
            this.path = path;

        }
        public void clearnameApath()
        {
            name = null;
            path = null;
        }
    }

    //遍历工具类
    public class ergodicDirBackPath
    {
        public static String inputxml = "";//目标弹幕文件全路径danmaku.xml
        public static String inputVideo = "";//目标视频文件全路径video.m4s
        public static String inputAudio = "";//目标音频文件全路径audio.m4s
        public static String inputJson = "";//目标音频文件全路径entry.json
        public static List<String> style_blv = new List<String>();//存储blv格式的文件名
        public static string blv_txtPath="";
        public static List<nameApath> json_pathList = new List<nameApath>();//存储名称和路径
        public static Regex regex = new Regex(@".*.blv$");


        //遍历download/111/11
        //获取P的名称下的danmaku.xml、audio.m4s、video.m4s
        public static void ergodicDirBackPathAboutm4s(String ergodicPath)
        {
            DirectoryInfo d = new DirectoryInfo(ergodicPath);
            FileSystemInfo[] fsinfos = d.GetFileSystemInfos();
            
            foreach (FileSystemInfo fsinfo in fsinfos)
            {
                if (fsinfo is DirectoryInfo)     //判断是否为文件夹
                {
                    ergodicDirBackPathAboutm4s(fsinfo.FullName);//递归调用
                }
                else
                {
                    FileInfo finfo = new FileInfo(fsinfo.FullName);
                    switch (finfo.Name)
                    {
                        case "danmaku.xml":
                            inputxml = finfo.FullName;
                            break;
                        case "video.m4s":
                            inputVideo = finfo.FullName;
                            break;
                        case "audio.m4s":
                            inputAudio = finfo.FullName;
                            break;
                        case "entry.json":
                            inputJson = finfo.FullName;
                            break;
                    }

                    if (regex.IsMatch(finfo.Name))
                    {

                        style_blv.Add(finfo.FullName);

                        if(style_blv.Count==1){
                            blv_txtPath = finfo.DirectoryName;//获取blv.txt文件的父目录也就是0.blv文件存在的目录
                        }


                        //MessageBox.Show(blv_txtPath);
                        //MessageBox.Show(finfo.FullName + "\n" + style_blv.Count + "\n");
                    }

                }
            }
            

        }


        //全路径download/111
        //大致地读取json--------每一个总标题只读一个P里的json用于显示总标题
        //获取标题的名称
        public static string roughlyPNameByReadJson(String ergodicPath)
        {
            DirectoryInfo d = new DirectoryInfo(ergodicPath);
            DirectoryInfo[] fsinfos = d.GetDirectories();
            try
            {
                inputJson = "";
                ergodicDirBackPathAboutm4s(fsinfos[0].FullName);//inputJson   json文件的路径
                
                return readjson(inputJson);//标题名//download/111/11
            }
            catch (Exception e)
            {
                //MessageBox.Show("roughlyReadJson出错:" + e.ToString());
                return "-1";
            }
        }



        //全路径download
        //大致地读取json--------每一个总标题只读一个P里的json用于显示总标题
        //获取标题的名称和路径
        public static List<nameApath> roughlyReadJson(String ergodicPath)
        {

            try
            {
                DirectoryInfo d = new DirectoryInfo(ergodicPath);
                DirectoryInfo[] fsinfos = d.GetDirectories();
                foreach (DirectoryInfo i in fsinfos)//download/111
                {
                    DirectoryInfo[] fsinfos2 = i.GetDirectories();//download/111/11
                    inputJson = "";
                    ergodicDirBackPathAboutm4s(fsinfos2[0].FullName);//inputJson   json文件的路径
                    json_pathList.Add(new nameApath(readjson(inputJson), i.FullName));//标题名、标题的路径//download/111/11

                }
            }
            catch (Exception e)
            {
                //MessageBox.Show("roughlyReadJson出错:" + e.ToString());
                json_pathList.Clear();
            }
            return json_pathList;
        }





        /// <summary>
        /// 读取Json文件内容字符串
        /// </summary>
        public static string GetJsonStr(string fileName)
        {
            string jsonStr = "";
            StreamReader sr = new StreamReader(fileName, Encoding.UTF8);
            string line;
            while ((line = sr.ReadLine()) != null)
            {
                jsonStr += line.ToString();
            }

            //json格式标准化处理
            jsonStr = jsonStr.Replace("{", "[{");
            jsonStr = jsonStr.Replace("}", "}]");
            int indexf = jsonStr.IndexOf("[");
            jsonStr = jsonStr.Remove(indexf, 1);
            int indexe = jsonStr.LastIndexOf("]");
            jsonStr = jsonStr.Remove(indexe, 1);

            return jsonStr;
        }


        /// <summary>
        /// readjson类
        /// </summary>
        public class RequestResult<T>
        {
            /// <summary>
            /// 主标题
            /// </summary>
            public string title { get; set; }

            /// <summary>
            /// avid
            /// </summary>
            public string avid { get; set; }


        }


        //读取download/1111/11下的json文件           json文件的路径
        //返回主题名
        public static String readjson(String path)
        {
            RequestResult<String> userResult=null;
            //读取Json文件内容
            string jsonStr = GetJsonStr(path);
            //MessageBox.Show(jsonStr);

            string result = "";

            
            try
            {
                //解析Json数据
                userResult = JsonConvert.DeserializeObject<RequestResult<String>>(jsonStr);
                result= userResult.title;
            }
            catch (Exception e)
            {
                try
                {
                    result= "AV号:" + userResult.avid;
                }
                catch (Exception e1)
                {
                    result= "获取标题失败,请进入查看";
                }
            }

            result = Regex.Replace(result, Main.regEx1, "");

            //MessageBox.Show(result);

            return result;


        }



        /// <summary>
        /// readjson2类
        /// </summary>
        public class RequestResult2<T>
        {
            /// <summary>
            /// P标题
            /// </summary>
            public T page_data { get; set; }

            /// <summary>
            /// avid
            /// </summary>
            public string avid { get; set; }

            public string total_bytes { get; set; }
            public string total_time_milli { get; set; }


        }


        /// <summary>
        /// readjson2类
        /// </summary>
        public class json2json
        {
            /// <summary>
            /// 章节标题
            /// </summary>
            public string part { get; set; }

            /// <summary>
            /// cid
            /// </summary>
            public string cid { get; set; }
        }

        //读取download/1111/11下的json文件           json文件的路径
        //返回p标题
        public static String readjson2(String path)
        {

            RequestResult2<List<json2json>> userResult = null;
            string readResult = "";//返回结果
            //读取Json文件内容
            string jsonStr = GetJsonStr(path);
            //解析Json数据
            userResult = JsonConvert.DeserializeObject<RequestResult2<List<json2json>>>(jsonStr);
            try
            {
                foreach (json2json i1 in userResult.page_data)
                {
                    readResult = i1.part;
                }
            }
            catch (Exception e)
            {
                try
                {
                    foreach (json2json i2 in userResult.page_data)
                    {
                        readResult = i2.cid;
                    }
                }
                catch (Exception e1)
                {
                    try
                    {
                        readResult = userResult.total_bytes;
                    }
                    catch (Exception e2)
                    {
                        readResult = userResult.total_time_milli;
                    }
                }
            }

            readResult = Regex.Replace(readResult, Main.regEx1, "");

            return readResult;

        }







        //    Json辅助方法返回p名称和路径
        //    download/111
        public static List<nameApath> getJsonFZ(String ergodicPath)
        {
            DirectoryInfo d = new DirectoryInfo(ergodicPath);
            DirectoryInfo[] fsinfos = d.GetDirectories();//download/111/11[]
            if (fsinfos != null)
            {
                foreach (DirectoryInfo i in fsinfos)//download/111/11
                {
                    inputJson = "";
                    ergodicDirBackPathAboutm4s(i.FullName);//inputJson   json文件的路径
                    json_pathList.Add(new nameApath(readjson2(inputJson), i.FullName));
                }

            }

            return json_pathList;
        }


        public static void clearPath()
        {
            inputxml = "";
            inputVideo = "";
            inputAudio = "";
            inputJson = "";
            json_pathList.Clear();
            style_blv.Clear();
        }

    }
}
